<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <el-date-picker v-model="selectDate" class="filter-item" type="month" placeholder="选择月" />
        <rrOperation :crud="crud" />
        <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
        <el-button type="primary" class="filter-item" size="mini" icon="el-icon-plus" @click="crud.toAdd">新 增</el-button>
        <span slot="right" class="filter-item" style="margin-left: 600px;">失能人员：{{ this.bisZhsqSnryXm }}</span>
      </div>
      <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="660px">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="方案日期" prop="farq">
                <el-date-picker v-if="isEdit" v-model="form.bisWhfaHwrq" type="date" placeholder="选择一个或多个日期" :picker-options="pickerOptions" style="width: 490px;" />
                <el-date-picker v-else v-model="farq" type="dates" placeholder="选择一个或多个日期" :picker-options="pickerOptions" style="width: 490px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="起始钟点" prop="bisWhfaStartTime">
                <el-time-select
                  v-model="form.bisWhfaStartTime"
                  :picker-options="{ start: '07:30', step: '00:10', end: '19:00' }"
                  placeholder="选择起始钟点"
                  style="width: 180px;"
                  @change="changeEndTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束钟点" prop="bisWhfaEndTime">
                <el-time-select
                  v-model="form.bisWhfaEndTime"
                  :picker-options="{ start: '09:30', step: '00:10', end: '21:00' }"
                  placeholder="选择起始钟点"
                  style="width: 180px;"
                  @change="changeEndTime"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="照护类别" prop="bisWhfaFwlx">
                <el-radio v-for="item in fwlx" :key="item.fwlxcode" v-model="form.bisWhfaFwlx" border :label="item.fwlxcode" @change="fwlxChange">{{ item.fwlxname }}</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="服务项目" prop="whfaFfxesChoose">
                <el-checkbox-group v-model="whfaFfxesChoose" size="mini" style="width: 480px;" @change="changeFwxm">
                  <el-checkbox v-for="item in viewCheckFwxm" :key="item.bisYmkdzId" :label="item.bisYmkdzId" border>{{ item.bisYmkdzMc }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="服务时长" prop="fwsc">
                <el-input v-model="fwsc" style="width: 180px;" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button v-if="isEdit" :loading="crud.status.cu === 2" type="primary" @click="doUpdate()">确认修改</el-button>
          <el-button v-else :loading="crud.status.cu === 2" type="primary" @click="doSave()">确认新增</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column align="center" prop="bisWhfaHwrq" label="方案实施日期" />
        <el-table-column align="center" prop="bisWhfaStartTime" label="起始钟点" />
        <el-table-column align="center" prop="bisWhfaEndTime" label="结束钟点" />
        <el-table-column align="center" prop="bisWhfaZt" label="方案状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.bisWhfaZt === '1'" effect="plain" type="">
              已生成订单
            </el-tag>
            <el-tag v-else-if="scope.row.bisWhfaZt === '0'" effect="plain" type="warning">
              未生成订单
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="bisWhfaFwlx" label="服务类型">
          <template slot-scope="scope">
            {{ dict.label.yllb[scope.row.bisWhfaFwlx] }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkPer(['admin','whfa:edit','whfa:del'])"
          label="操作"
          width="115"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudWhfa from '@/api/business/whfa'
import { queryHljgFwxm } from '@/api/business/ymkdz'
import CRUD, { presenter, header, form } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import moment from 'moment'

const defaultForm = { bisWhfaId: null, bisWhfaZhsqId: null, bisWhfaHwrq: null, bisWhfaStartTime: null, bisWhfaEndTime: null, bisWhfaZt: null, bisWhfaFwlx: null, whfaFfxes: [] }
export default {
  name: 'Whfa',
  components: { pagination, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm)],
  dicts: ['xb', 'yjsgx', 'ccs', 'zhzt', 'ccstcqh', 'qygl', 'yllb'],
  cruds() {
    return CRUD({ title: '维护方案', url: 'api/whfa', idField: 'bisWhfaId', sort: 'bisWhfaHwrq,desc', crudMethod: { ...crudWhfa }})
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      bisZhsqSnryXm: '',
      pop: false,
      approveDialog: false,
      selectedZhids: [],
      bisGsglId: '',
      selectDate: new Date(),
      farq: '',
      whrqs: '',
      whfaFfxesChoose: [],
      viewCheckFwxm: [],
      fwxm: [],
      fwlx: [],
      fwsc: 0,
      scFlag: false,
      isEdit: false,
      permission: {
        add: ['admin', 'whfa:add'],
        edit: ['admin', 'whfa:edit'],
        del: ['admin', 'whfa:del']
      },
      rules: {
        bisWhfaStartTime: [
          { required: true, message: '起始钟点不能为空', trigger: 'blur' }
        ],
        bisWhfaEndTime: [
          { required: true, message: '结束钟点不能为空', trigger: 'blur' }
        ],
        bisWhfaFwlx: [
          { required: true, message: '服务类型不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.query.bisWhfaZhsqId = this.$route.query.bisWhfaZhsqId
    this.bisZhsqSnryXm = this.$route.query.bisZhsqSnryXm
  //  this.queryHljgFwxm()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.query.bisWhfaZhsqId = this.$route.query.bisWhfaZhsqId
      this.query.bisWhfaHwrq = moment(this.selectDate).format('YYYY-MM')
      return true
    },
    [CRUD.HOOK.beforeToAdd]() {
      this.isEdit = false
      this.whfaFfxesChoose = []
      this.fwlx = []
      this.fwxm = []
      this.farq = ''
      this.queryHljgFwxm()
      console.log('this.fwlx: {} ', this.fwlx)
      return true
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      if (form.bisWhfaZt === '1') {
        this.$notify({
          title: '方案已经生成订单，无法更改',
          type: 'warning',
          duration: 2500
        })
        return false
      }
      this.isEdit = true
      this.whfaFfxesChoose = []
      this.fwlx = []
      this.fwxm = []
      this.farq = ''
      this.queryHljgFwxm()

      setTimeout(() => {
        this.form.bisWhfaFwlx = this.form.bisWhfaFwlx === '94' ? '01' : this.form.bisWhfaFwlx
        this.form.bisWhfaFwlx = this.form.bisWhfaFwlx === '95' ? '04' : this.form.bisWhfaFwlx

        this.fwlxChange(this.form.bisWhfaFwlx)
        for (const item of this.form.whfaFfxes) {
          this.whfaFfxesChoose.push(item.bisWhfaDzid)
        }
        this.changeFwxm(this.form.bisWhfaFwlx)
      }, 1000)

      return true
    },
    changeEndTime(v) {
    },
    fwlxChange(e) {
      for (const item of this.fwxm) {
        const fwlxcode = item.fwlxcode
        if (e === fwlxcode) {
          this.viewCheckFwxm = item.fwxmList
        }
      }
    },
    changeFwxm(e) {
      this.fwsc = 0
      for (const item of this.fwxm) {
        console.log(item.fwlxcode)
        console.log(this.form.bisWhfaFwlx)
        if (item.fwlxcode === this.form.bisWhfaFwlx) {
          for (const item2 of item.fwxmList) {
            if (this.whfaFfxesChoose.indexOf(item2.bisYmkdzId) > -1) {
              this.fwsc = this.fwsc + (item2.bisYmkdzFwsc - 0)
              if (this.fwsc > 120) {
                this.scFlag = true
                this.$notify({
                  title: '服务时长不允许超过120分钟',
                  type: 'warning',
                  duration: 2500
                })
              } else {
                this.scFlag = false
              }
            }
          }
        }
      }
    },
    queryHljgFwxm() {
      queryHljgFwxm().then(res => {
        this.fwxm = res
        this.fwlx = res
      }).catch(() => { })
    },
    /**
     * 自定义保存
     * @param zt
     */
    doSave() {
      if (this.form.bisWhfaFwlx === '01') {
        if (this.farq.length > 8) {
          this.$notify({
            title: '生活照料最多8天',
            type: 'warning',
            duration: 2500
          })
          return false
        }
      }
      if (this.form.bisWhfaFwlx === '04') {
        if (this.farq.length > 4) {
          this.$notify({
            title: '医疗护理最多4天',
            type: 'warning',
            duration: 2500
          })
          return false
        }
      }
      const titleMsg = '保存成功'
      this.form.bisWhfaZhsqId = this.$route.query.bisWhfaZhsqId
      // 服务项目明细
      this.form.whfaFfxes = []
      for (const item of this.whfaFfxesChoose) {
        this.form.whfaFfxes.push({ bisWhfaDzid: item })
      }
      // 维护日期
      this.form.bisWhfaHwrq = ''
      for (const item of this.farq) {
        const date1 = moment(item).format('YYYY-MM-DD')
        this.form.bisWhfaHwrq += date1 + ','
      }
      // 判断是否超过120分钟
      if (this.scFlag) {
        this.$notify({
          title: '服务时长不允许超过120分钟',
          type: 'warning',
          duration: 2500
        })
        return false
      }
      this.crud.findVM('form').$refs['form'].validate(valid => {
        if (!valid) {
          return
        }

        if (this.crud.status.add === 1 && this.crud.status.edit === 0) { // 点击新增按钮，提交的时候只是新增
          this.crud.status.add = CRUD.STATUS.PROCESSING
          crudWhfa.createZhfa(this.form)
            .then(res => {
              this.crud.status.add = CRUD.STATUS.NORMAL
              this.$notify({
                title: titleMsg,
                type: 'success',
                duration: 2500
              })
              this.crud.toQuery()
            })
            .catch(err => {
              this.crud.status.add = CRUD.STATUS.PREPARED
              console.log(err)
            })
        }
      })
    },
    /**
     * 自定义修改
     * @param zt
     */
    doUpdate() {
      const titleMsg = '修改成功'
      this.form.bisWhfaZhsqId = this.$route.query.bisWhfaZhsqId
      // 服务项目明细
      this.form.whfaFfxes = []
      for (const item of this.whfaFfxesChoose) {
        this.form.whfaFfxes.push({ bisWhfaDzid: item })
      }
      this.form.bisWhfaHwrq = moment(this.form.bisWhfaHwrq).format('YYYY-MM-DD')
      // 判断是否超过120分钟
      if (this.scFlag) {
        this.$notify({
          title: '服务时长不允许超过120分钟',
          type: 'warning',
          duration: 2500
        })
        return false
      }
      this.crud.findVM('form').$refs['form'].validate(valid => {
        if (!valid) {
          return
        }

        if (this.crud.status.add === 0 && this.crud.status.edit === 1) { // 点击修改按钮，提交的时候只是修改
          this.crud.status.edit = CRUD.STATUS.PROCESSING
          crudWhfa.edit(this.form)
            .then(res => {
              this.crud.status.edit = CRUD.STATUS.NORMAL
              this.$notify({
                title: titleMsg,
                type: 'success',
                duration: 2500
              })
              this.crud.toQuery()
            })
            .catch(err => {
              this.crud.status.edit = CRUD.STATUS.PREPARED
              console.log(err)
            })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
